require 'xmpp4r'
require 'xmpp4r/roster/helper/roster'


class Login 
	
	def initialize id, password
		
		puts 'new model initialized'
		#connect
	    @mesage= Array.new
		@mesage << Jabber::Message::new('shishir.srivastava@oracle.com', '').set_type(:normal).set_id('1')
		@mesage[0].from='shishir.srivastava@oracle.com'
		@buddies=Hash.new
		@jid = id
		@new=false
		@thr = Thread.current		
		@jid.domain='oracle.com'
		@password = password
		@cl = Jabber::Client::new(@jid)
		@cl.connect(host='im.oracle.com', port=5223)
		@cl.auth_nonsasl(@password,false)
		#@sid=Jabber::IdGenerator::generate_id()
		#@cl.send(Jabber::Presence::new(show=nil,status='logged in from ruby',nil))
		#msg=Jabber::Message::new('shishir.srivastava@oracle.com', 'welcome from model connect').set_type(:normal).set_id('1')
		#@cl.send msg
		
		@roster = Jabber::Roster::Helper::new(@cl)
		@roster.add_query_callback { |iq|
	    build_roster
		}

		@cl.add_message_callback do |m|
		if m.type != :error
			@mesage << m
			if @thr.stop?
			 @thr.wakeup
			 puts 'thread waking up'
			 else
			 puts 'thread is already awake'
			end
			@new=true			 
			#create_message("Acknowledged: #{m.body}"+" \n Send \'exit\' to close", m.from)
			if m.body == 'exit'
				create_message("OK..Gud bye...", m.from)
				@cl.close
			end    	
		end
		end 
end  #end of initialize 
    
	def build_roster
	@roster.groups.each { |group|
		if group.nil?
		puts "*** Ungrouped ***"
		else
			puts "*** #{group} ***"
		end
		@roster.find_by_group(group).each { |item|
		puts "- #{item.iname} (#{item.jid})"
		@buddies[item.jid]=item.iname
		}
		}
	end
	
	def get_buddies
	return @buddies
	end
	
	def throw
		@thr=Thread.current
		p @thr
		#hasnew
		Thread.stop
		@new=false
		temp = @mesage
		@mesage=Jabber::Message::new()
		return temp
	end
	
	def hasnew
		x=Thread.new {sleep(0.5) while !@new
					Thread.exit
					return nil}
		x.join
	end

	def transmit(msg)
	@cl.send msg
	end

	def create_message(body, to_jid)
		to_jid = Jabber::JID.new('shishir.srivastava@oracle.com')
		m = Jabber::Message::new(to_jid, body).set_type(:normal).set_id('1')
		transmit m
		#redirect_to :action => 'index'end
	end
end